<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="出库类型" prop="outboundType">
        <el-input
            v-model="queryParams.outboundType"
            placeholder="请输入出库类型"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="deliveryOutboundList" @selection-change="handleSelectionChange">
      <el-table-column label="出库单号" align="center" prop="deliveryOrderNumber" />
      <el-table-column label="客户名称" align="center" prop="cusName" />
      <el-table-column label="产品名称" align="center" prop="issueMaterialName" />
      <el-table-column label="产品编码" align="center" prop="issueMaterialCode" />
      <el-table-column label="产品类型" align="center" prop="issueMaterialType" />
      <el-table-column label="出库数量" align="center" prop="issueOutboundQuantity" />
      <el-table-column label="出库时间" align="center" prop="confirmDeliveryTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.confirmDeliveryTime ? parseTime(scope.row.confirmDeliveryTime, '{y}-{m}-{d}') : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleDetail(scope.row)"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 主产品采购订单详情弹窗 -->
    <el-dialog :title="detailDialogTitle" :visible.sync="detailDialogVisible" width="80%" append-to-body @close="handleDialogClose">
      <!-- 物料编码标签页 -->
      <el-tabs v-model="activeMaterialCode" @tab-click="handleTabClick" v-if="materialTabs.length > 0">
        <el-tab-pane
            v-for="tab in materialTabs"
            :key="tab.code"
            :label="tab.code"
            :name="tab.code">
          <div style="margin-top: 5px; font-size: 12px; color: #666;">
            <span>{{ tab.name }}</span>
            <el-button
                v-if="isSemiFinishedProductByName(tab.name)"
                size="mini"
                type="text"
                @click="handleSubDetailByTab(tab)"
                style="padding: 0; margin-left: 5px; color: #409EFF;"
            >详情</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>

      <!-- 采购订单详情表格 -->
      <el-table v-loading="detailLoading" :data="procurementOrderList">
        <el-table-column label="物料编码" align="center" prop="purcMaterialCode" />
        <el-table-column label="物料名称" align="center" prop="purcMaterialName" />
        <el-table-column label="采购数量" align="center" prop="purcQuantityDemand" />
        <el-table-column label="采购单价" align="center" prop="purcUnitPrice" />
        <el-table-column label="总金额(元)" align="center" prop="purcTotalAmount" />
        <el-table-column label="采购单位" align="center" prop="purcPurchasingUnit" />
        <el-table-column label="物料类型" align="center" prop="purcMaterialType" />
        <el-table-column label="所属仓库" align="center" prop="purcWarehouse" />
        <el-table-column label="采购时间" align="center" prop="orderDate" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.orderDate ? parseTime(scope.row.orderDate, '{y}-{m}-{d}') : '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="申请人" align="center" prop="applicant" />
      </el-table>

      <div v-if="materialTabs.length === 0 && !detailLoading">
        <el-empty description="暂无采购订单数据"></el-empty>
      </div>

      <pagination
          v-show="detailTotal>0"
          :total="detailTotal"
          :page.sync="detailQueryParams.pageNum"
          :limit.sync="detailQueryParams.pageSize"
          @pagination="getProcurementDetailsByMaterialCode"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleDialogClose">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 半成品采购订单详情弹窗 -->
    <el-dialog :title="subDetailDialogTitle" :visible.sync="subDetailDialogVisible" width="80%" append-to-body @close="handleSubDialogClose">
      <!-- 半成品物料编码标签页 -->
      <el-tabs v-model="subActiveMaterialCode" @tab-click="handleSubTabClick" v-if="subMaterialTabs.length > 0">
        <el-tab-pane
            v-for="tab in subMaterialTabs"
            :key="tab.code"
            :label="tab.code"
            :name="tab.code">
          <div style="margin-top: 5px; font-size: 12px; color: #666;">
            <span>{{ tab.name }}</span>
            <el-button
                v-if="isSemiFinishedProductByName(tab.name)"
                size="mini"
                type="text"
                @click="handleSubDetailByTab(tab)"
                style="padding: 0; margin-left: 5px; color: #409EFF;"
            >详情</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>

      <!-- 半成品采购订单详情表格 -->
      <el-table v-loading="subDetailLoading" :data="subProcurementOrderList">
        <el-table-column label="物料编码" align="center" prop="purcMaterialCode" />
        <el-table-column label="物料名称" align="center" prop="purcMaterialName" />
        <el-table-column label="采购数量" align="center" prop="purcQuantityDemand" />
        <el-table-column label="采购单价" align="center" prop="purcUnitPrice" />
        <el-table-column label="总金额(元)" align="center" prop="purcTotalAmount" />
        <el-table-column label="采购单位" align="center" prop="purcPurchasingUnit" />
        <el-table-column label="物料类型" align="center" prop="purcMaterialType" />
        <el-table-column label="所属仓库" align="center" prop="purcWarehouse" />
        <el-table-column label="采购时间" align="center" prop="orderDate" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.orderDate ? parseTime(scope.row.orderDate, '{y}-{m}-{d}') : '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="申请人" align="center" prop="applicant" />
      </el-table>

      <div v-if="subMaterialTabs.length === 0 && !subDetailLoading">
        <el-empty description="暂无采购订单数据"></el-empty>
      </div>

      <pagination
          v-show="subDetailTotal>0"
          :total="subDetailTotal"
          :page.sync="subDetailQueryParams.pageNum"
          :limit.sync="subDetailQueryParams.pageSize"
          @pagination="getSubProcurementDetailsByMaterialCode"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleSubDialogClose">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDeliveryOutboundList, getProcurementDetails, getBomMaterial, getBomItemDetails } from "@/api/mes/md/procurement";

export default {
  name: "OrderProcurement",
  data() {
    return {
      // 遮罩层
      loading: true,
      detailLoading: false,
      subDetailLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      detailTotal: 0,
      subDetailTotal: 0,
      // 发货出库表格数据
      deliveryOutboundList: [],
      // 采购订单详情数据
      procurementOrderList: [],
      subProcurementOrderList: [],
      // 物料标签页数据
      materialTabs: [],
      subMaterialTabs: [],
      // 当前激活的物料编码
      activeMaterialCode: '',
      subActiveMaterialCode: '',
      // 弹窗标题
      detailDialogTitle: "",
      subDetailDialogTitle: "",
      // 弹窗显示状态
      detailDialogVisible: false,
      subDetailDialogVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        outboundType: "发货出库"
      },
      detailQueryParams: {
        pageNum: 1,
        pageSize: 10,
        itemCode: undefined
      },
      subDetailQueryParams: {
        pageNum: 1,
        pageSize: 10,
        itemCode: undefined
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询发货出库列表 */
    getList() {
      this.loading = true;
      getDeliveryOutboundList(this.queryParams).then(response => {
        if (response.rows && Array.isArray(response.rows)) {
          this.deliveryOutboundList = response.rows.filter(item => item !== null);
        } else {
          this.deliveryOutboundList = [];
        }
        this.total = response.total || 0;
        this.loading = false;
      }).catch(error => {
        console.error('获取数据失败:', error);
        this.deliveryOutboundList = [];
        this.total = 0;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 处理选择变化 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.itemId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 判断是否为半成品（根据物料类型） */
    isSemiFinishedProduct(row) {
      return row.purcMaterialType && row.purcMaterialType.includes('半成品');
    },
    /** 判断是否为半成品（根据物料名称） */
    isSemiFinishedProductByName(name) {
      return name && name.includes('半成品');
    },
    /** 通过标签页查看半成品详情 */
    handleSubDetailByTab(tab) {
      // 重置半成品相关数据
      this.resetSubDetailData();

      // 设置当前行的参数
      this.subDetailQueryParams.itemCode = tab.code;
      this.subDetailDialogTitle = `半成品采购订单详情 - ${tab.name}(${tab.code})`;
      this.subDetailDialogVisible = true;

      // 异步获取详情数据
      this.$nextTick(() => {
        // 首先获取BOM物料详情来构建标签页
        getBomItemDetails({ issueMaterialCode: tab.code }).then(response => {
          if (response.rows && response.rows.length > 0) {
            this.subMaterialTabs = response.rows.map(item => ({
              code: item.itemCode,
              name: item.itemName
            }));
            this.sortMaterialTabs();

            // 默认激活第一个标签并获取其采购订单详情
            if (this.subMaterialTabs.length > 0) {
              this.subActiveMaterialCode = this.subMaterialTabs[0].code;
              // 更新查询参数为当前选中的标签页物料编码
              this.subDetailQueryParams.itemCode = this.subActiveMaterialCode;
              this.getSubProcurementDetailsByMaterialCode();
            }
          } else {
            // 如果没有BOM详情，则直接使用当前物料编码查询采购详情
            this.subDetailQueryParams.itemCode = tab.code;
            this.getSubProcurementDetailsByMaterialCode();
          }
        }).catch(err => {
          this.msgError("获取BOM物料详情失败");
        });
      });
    },
    /** 查看主产品详情 */
    handleDetail(row) {
      // 重置相关数据
      this.resetDetailData();

      // 设置当前行的参数（用于初始BOM获取）
      this.detailQueryParams.itemCode = row.issueMaterialCode;
      this.detailDialogTitle = `采购订单详情 - ${row.issueMaterialName}(${row.issueMaterialCode})`;
      this.detailDialogVisible = true;

      // 异步获取详情数据
      this.$nextTick(() => {
        // 首先获取BOM物料详情来构建标签页
        getBomItemDetails({ issueMaterialCode: row.issueMaterialCode }).then(response => {
          if (response.rows && response.rows.length > 0) {
            this.materialTabs = response.rows.map(item => ({
              code: item.itemCode,
              name: item.itemName
            }));
            this.sortMaterialTabs();

            // 默认激活第一个标签并获取其采购订单详情
            if (this.materialTabs.length > 0) {
              this.activeMaterialCode = this.materialTabs[0].code;
              // 更新查询参数为当前选中的标签页物料编码
              this.detailQueryParams.itemCode = this.activeMaterialCode;
              this.getProcurementDetailsByMaterialCode();
            }
          }
        }).catch(err => {
          this.msgError("获取BOM物料详情失败");
        });
      });
    },
    /** 查看半成品详情 */
    handleSubDetail(row) {
      // 重置半成品相关数据
      this.resetSubDetailData();

      // 设置当前行的参数
      this.subDetailQueryParams.itemCode = row.purcMaterialCode;
      this.subDetailDialogTitle = `半成品采购订单详情 - ${row.purcMaterialName}(${row.purcMaterialCode})`;
      this.subDetailDialogVisible = true;

      // 异步获取详情数据
      this.$nextTick(() => {
        // 首先获取BOM物料详情来构建标签页
        getBomItemDetails({ issueMaterialCode: row.purcMaterialCode }).then(response => {
          if (response.rows && response.rows.length > 0) {
            this.subMaterialTabs = response.rows.map(item => ({
              code: item.itemCode,
              name: item.itemName
            }));
            this.sortMaterialTabs();

            // 默认激活第一个标签并获取其采购订单详情
            if (this.subMaterialTabs.length > 0) {
              this.subActiveMaterialCode = this.subMaterialTabs[0].code;
              // 更新查询参数为当前选中的标签页物料编码
              this.subDetailQueryParams.itemCode = this.subActiveMaterialCode;
              this.getSubProcurementDetailsByMaterialCode();
            }
          } else {
            // 如果没有BOM详情，则直接使用当前物料编码查询采购详情
            this.subDetailQueryParams.itemCode = row.purcMaterialCode;
            this.getSubProcurementDetailsByMaterialCode();
          }
        }).catch(err => {
          this.msgError("获取BOM物料详情失败");
        });
      });
    },
    /** 获取主产品采购订单详情 */
    getProcurementDetailsByMaterialCode() {
      // 使用当前选中的标签页物料编码
      if (!this.detailQueryParams.itemCode) {
        return;
      }
      this.detailLoading = true;

      // 获取采购详情（只获取当前标签页对应的物料）
      getProcurementDetails(this.detailQueryParams).then(procurementResponse => {
        this.procurementOrderList = procurementResponse.rows;
        // 按采购时间倒序排列
        this.procurementOrderList.sort((a, b) => {
          if (a.orderDate && b.orderDate) {
            return new Date(b.orderDate) - new Date(a.orderDate);
          }
          return 0;
        });
        this.detailTotal = procurementResponse.total;
        this.detailLoading = false;
      }).catch(err => {
        this.procurementOrderList = [];
        this.detailTotal = 0;
        this.detailLoading = false;
        this.msgError("获取采购订单详情失败");
      });
    },
    /** 获取半成品采购订单详情 */
    getSubProcurementDetailsByMaterialCode() {
      if (!this.subDetailQueryParams.itemCode) {
        return;
      }
      this.subDetailLoading = true;

      // 获取采购详情（只获取当前标签页对应的物料）
      getProcurementDetails(this.subDetailQueryParams).then(procurementResponse => {
        this.subProcurementOrderList = procurementResponse.rows;
        // 按采购时间倒序排列
        this.subProcurementOrderList.sort((a, b) => {
          if (a.orderDate && b.orderDate) {
            return new Date(b.orderDate) - new Date(a.orderDate);
          }
          return 0;
        });
        this.subDetailTotal = procurementResponse.total;
        this.subDetailLoading = false;
      }).catch(err => {
        this.subProcurementOrderList = [];
        this.subDetailTotal = 0;
        this.subDetailLoading = false;
        this.msgError("获取半成品采购订单详情失败");
      });
    },
    /** 对物料标签进行排序，将包含"半成品"的标签放在第一个 */
    sortMaterialTabs() {
      this.materialTabs.sort((a, b) => {
        const aIsSemi = a.name.includes('半成品') ? 0 : 1;
        const bIsSemi = b.name.includes('半成品') ? 0 : 1;
        return aIsSemi - bIsSemi;
      });

      // 同样对半成品标签进行排序
      this.subMaterialTabs.sort((a, b) => {
        const aIsSemi = a.name.includes('半成品') ? 0 : 1;
        const bIsSemi = b.name.includes('半成品') ? 0 : 1;
        return aIsSemi - bIsSemi;
      });
    },
    /** 标签页点击事件 */
    handleTabClick(tab) {
      // 更新当前选中的物料编码
      this.activeMaterialCode = tab.name;

      // 当标签页切换时，重新获取采购订单详情
      this.detailQueryParams.itemCode = tab.name;
      this.getProcurementDetailsByMaterialCode();
    },
    /** 半成品标签页点击事件 */
    handleSubTabClick(tab) {
      // 更新当前选中的物料编码
      this.subActiveMaterialCode = tab.name;

      // 当标签页切换时，重新获取采购订单详情
      this.subDetailQueryParams.itemCode = tab.name;
      this.getSubProcurementDetailsByMaterialCode();
    },
    /** 主弹窗关闭事件 */
    handleDialogClose() {
      this.detailDialogVisible = false;
      this.resetDetailData();
    },
    /** 半成品弹窗关闭事件 */
    handleSubDialogClose() {
      this.subDetailDialogVisible = false;
      this.resetSubDetailData();
    },
    /** 重置主产品详情数据 */
    resetDetailData() {
      this.procurementOrderList = [];
      this.materialTabs = [];
      this.activeMaterialCode = '';
      this.detailTotal = 0;
      this.detailLoading = false;
      this.detailQueryParams = {
        pageNum: 1,
        pageSize: 10,
        itemCode: undefined
      };
    },
    /** 重置半成品详情数据 */
    resetSubDetailData() {
      this.subProcurementOrderList = [];
      this.subMaterialTabs = [];
      this.subActiveMaterialCode = '';
      this.subDetailTotal = 0;
      this.subDetailLoading = false;
      this.subDetailQueryParams = {
        pageNum: 1,
        pageSize: 10,
        itemCode: undefined
      };
    }
  }
};
</script>
